/*
 * Copyright (c) 2021
 * User:魔金多商户商城
 * File:IndexController.java
 * Date:2020/09/13 08:43:13
 */

package com.ruoyi.tc;


import com.ruoyi.appletsutil.AppletsLoginUtils;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.UnAuth;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.md5.MD5Utils;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.bean.OssSetting;
import com.ruoyi.common.utils.bean.PrepayResult;
import com.ruoyi.common.utils.bean.WechatNotifyResult;
import com.ruoyi.login.AppletConfig;
import com.ruoyi.setting.service.OssService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.tc.domain.*;
import com.ruoyi.tc.service.*;
import com.ruoyi.tc.vo.TcMemberLevelVo;
import com.ruoyi.tc.vo.TcPayVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Auther: shenzhuan
 * @Date: 2019/4/2 15:02
 * @Description:
 */
@Slf4j
@RestController
@Api(tags = "IndexController", description = "home")
public class TcPublishController extends BaseController {
    /**
     * 成功
     */
    public final static String SUCCESS = "SUCCESS";
    /**
     * 微信支付统一下单地址
     */
    private final static String UNION_SUBMIT_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    /**
     * 获取ip地址用
     */
    private static final String UNKNOWN = "unknown";
    @Resource
    private ITcZhuanlangService tcZhuanlangService;
    @Resource
    private ITcGoodsService tcGoodsService;
    @Resource
    private ITcTuiguangService tcTuiguangService;
    @Resource
    private ITcQiugouService tcQiugouService;
    @Resource
    private ITcNonglinService tcNonglinService;
    @Resource
    private ITcCarService tcCarService;
    @Autowired
    private ITcRoomService tcRoomService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private ITcJobService tcJobService;
    @Resource
    private ITcNavService tcNavService;
    @Autowired
    private ITcJobClassService tcJobClassService;
    @Autowired
    private ITcAdService tcAdService;
    @Autowired
    private ITcMemberService memberService;
    @Autowired
    private ITcMemberLevelService memberLevelService;
    @Autowired
    private ITcStoreInfoService tcStoreInfoService;
    @Autowired
    private ITcStroeCommentService stroeCommentService;
    @Autowired
    private ITcMemberService tcMemberService;
    @Autowired
    private ITcUserCardService userCardService;
    @Autowired
    private ITcDepositRecordService depositRecordService;
    @Autowired
    private ITcOrderService orderService;
    /**
     * 注入序列生成器
     */
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Resource
    private OssService ossService;

    /**
     * 验证返回信息
     *
     * @param inputStream 微信回调信息
     * @return 订单支付信息
     */
    public static TcDepositRecord afterPayInfo(InputStream inputStream) {

        TcDepositRecord orderInfoAfterPay = new TcDepositRecord();
        BufferedReader br;
        br = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuilder sb = new StringBuilder();
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                br.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //将xml字符串转换为java对象
        JaxbUtil resultBinder = new JaxbUtil(WechatNotifyResult.class);
        WechatNotifyResult wechatNotifyResult = resultBinder.fromXml(sb.toString());
        //将xml字符串转换为map
        SortedMap<String, String> resultMap = new TreeMap<>(parseMapFromXmlStr(sb.toString()));
        //签名
        String sign = createSign(resultMap, AppletConfig.WECHATAPPLET.apiKey);

        log.info("wechat notify and wechatNotifyResult :{}", wechatNotifyResult);

        //验证是否失败，并验证签名
        if (!wechatNotifyResult.isError() && sign.equals(wechatNotifyResult.getSign())) {
            //验证其他信息
            if (SUCCESS.equals(wechatNotifyResult.getResult_code())
                    && SUCCESS.equals(wechatNotifyResult.getReturn_code())
                    && AppletConfig.WECHATAPPLET.appId.equals(wechatNotifyResult.getAppid())
                    && AppletConfig.WECHATAPPLET.merchantNum.equals(wechatNotifyResult.getMch_id())
            ) {
                orderInfoAfterPay.setId(Long.parseLong(wechatNotifyResult.getOut_trade_no().split("-")[0]));

                orderInfoAfterPay.setStatus("2");
                orderInfoAfterPay.setOutTradeNo(wechatNotifyResult.getTransaction_id());
            }

        } else {
            log.error("wechat afterPayInfo fail: returnmsg:{}\r\n errormsg:{}", wechatNotifyResult.getReturn_msg(), wechatNotifyResult.getErr_code_des());
        }
        return orderInfoAfterPay;
    }

    /**
     * 将xml字符串转换成map
     *
     * @param xml xml
     * @return Map
     */
    private static Map<String, String> parseMapFromXmlStr(String xml) {
        Map<String, String> map = new HashMap<>();
        Document doc;
        try {
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            List<Element> list = rootElt.elements();//获取根节点下所有节点
            for (Element element : list) {  //遍历节点
                map.put(element.getName(), element.getText()); //节点的name为map的key，text为map的value
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 获取预支付信息
     *
     * @param orderBase 订单信息
     * @return 预支付信息
     */
    public static PrepayResult getPrepay(TcOrder orderBase) {
        String xml = getWxPayParm(orderBase);
        String res = executeHttpPost(UNION_SUBMIT_ORDER_URL, xml);
        log.debug("getPrepay and res:{}", res);

        //将xml字符串转换为java对象
        JaxbUtil resultBinder = new JaxbUtil(PrepayResult.class);
        PrepayResult prepayResult = resultBinder.fromXml(res);
        if (!prepayResult.isError()) {
            SortedMap<String, String> packageParams = new TreeMap<>();
            prepayResult.setPackage();
            prepayResult.setSign_type("MD5");
            prepayResult.setTime_stamp(getTimeStamp());
            packageParams.put("appId", prepayResult.getAppid());
            packageParams.put("timeStamp", prepayResult.getTime_stamp());
            packageParams.put("nonceStr", prepayResult.getNonce_str());
            packageParams.put("package", prepayResult.getPackage_());
            packageParams.put("signType", prepayResult.getSign_type());
            prepayResult.setPay_sign(createSign(packageParams, AppletConfig.WECHATAPPLET.apiKey));
            prepayResult.setResult_code(orderBase.getId() + "");
            return prepayResult;
        } else {
            if (!StringUtils.isEmpty(prepayResult.getErr_code_des())) {
                log.error("getPrepay Fail and returnmsg:{} \r\n errormsg:{} ", prepayResult.getReturn_msg(), prepayResult.getErr_code_des());
            }
            return null;
        }
    }

    /**
     * 获取预支付信息
     *
     * @param orderBase 订单信息
     * @return 预支付信息
     */
    public static PrepayResult getPrepay(TcDepositRecord orderBase) {
        String xml = getWxPayParm(orderBase);
        String res = executeHttpPost(UNION_SUBMIT_ORDER_URL, xml);
        log.debug("getPrepay and res:{}", res);

        //将xml字符串转换为java对象
        JaxbUtil resultBinder = new JaxbUtil(PrepayResult.class);
        PrepayResult prepayResult = resultBinder.fromXml(res);
        if (!prepayResult.isError()) {
            SortedMap<String, String> packageParams = new TreeMap<>();
            prepayResult.setPackage();
            prepayResult.setSign_type("MD5");
            prepayResult.setTime_stamp(getTimeStamp());
            packageParams.put("appId", prepayResult.getAppid());
            packageParams.put("timeStamp", prepayResult.getTime_stamp());
            packageParams.put("nonceStr", prepayResult.getNonce_str());
            packageParams.put("package", prepayResult.getPackage_());
            packageParams.put("signType", prepayResult.getSign_type());
            prepayResult.setPay_sign(createSign(packageParams, AppletConfig.WECHATAPPLET.apiKey));
            prepayResult.setResult_code(orderBase.getId() + "");
            return prepayResult;
        } else {
            if (!StringUtils.isEmpty(prepayResult.getErr_code_des())) {
                log.error("getPrepay Fail and returnmsg:{} \r\n errormsg:{} ", prepayResult.getReturn_msg(), prepayResult.getErr_code_des());
            }
            return null;
        }
    }

    /**
     * 执行GET方法请求数据
     *
     * @param url 请求地址
     * @return 返回数据
     */
    static String executeHttpGet(String url) {
        log.debug("executeHttpGet and url:{}", url);
        String result = null;
        BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", SSLConnectionSocketFactory.getSocketFactory())
                        .build(),
                null,
                null,
                null
        );

        HttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(connManager)
                .build();

        HttpGet httpRequest = new HttpGet(url);

        try {
            //使用DefaultHttpClient类的execute方法发送HTTP GET请求，并返回HttpResponse对象。
            HttpResponse httpResponse = httpClient.execute(httpRequest);//其中HttpGet是HttpUriRequst的子类
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity, "UTF-8");//取出应答字符串

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 执行POST方法请求数据
     *
     * @param url 请求地址
     * @param xml 请求参数
     * @return 返回数据
     */
    public static String executeHttpPost(String url, String xml) {
        log.debug("executeHttpPost and url:{}", url);
        String result = null;
        BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", SSLConnectionSocketFactory.getSocketFactory())
                        .build(),
                null,
                null,
                null
        );

        HttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(connManager)
                .build();
        HttpPost httpRequest = new HttpPost(url);

        try {
            httpRequest.setEntity(new StringEntity(xml, "UTF-8"));
            //使用DefaultHttpClient类的execute方法发送HTTP GET请求，并返回HttpResponse对象。
            HttpResponse httpResponse = httpClient.execute(httpRequest);//其中HttpGet是HttpUriRequst的子类
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity, "UTF-8");//取出应答字符串

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取统一下单请求参数
     *
     * @param orderInfoForPay 订单信息
     * @return 统一下单请求参数
     */
    private static String getWxPayParm(TcDepositRecord orderInfoForPay) {
        SortedMap<String, String> packageParams = new TreeMap<>();
        // 金额转化为分为单位
        int finalmoney = Integer.parseInt(String.format("%.2f", orderInfoForPay.getPayAmount()).replace(".", ""));
        //交易方式
        String tradeType = "JSAPI";
        //用户唯一标识
        packageParams.put("openid", orderInfoForPay.getOpenid());

        //公众账号ID
        packageParams.put("appid", AppletConfig.WECHATAPPLET.appId);
        //商户号
        packageParams.put("mch_id", AppletConfig.WECHATAPPLET.merchantNum);
        //随机字符串
        packageParams.put("nonce_str", getRandomString());
        //商品描述
        packageParams.put("body", "会员充值");
        //附加数据(支付类型) 订单还是充值 店铺编号 支付方式
        // packageParams.put("attach", orderInfoForPay.getType() + "-"+orderInfoForPay.getStoreId()+"-"+wechatSetting.getType());
        packageParams.put("attach", orderInfoForPay.getMonthCount() + "");
        //商户订单号
        packageParams.put("out_trade_no", orderInfoForPay.getId() + "-" + getTimeStamp());
        //标价金额
        packageParams.put("total_fee", String.valueOf(finalmoney));
        //终端IP
        packageParams.put("spbill_create_ip", orderInfoForPay.getIp());//本地测试需替换为外网ip
        //通知地址
        packageParams.put("notify_url", AppletConfig.WECHATAPPLET.payCallback);
        //交易类型
        packageParams.put("trade_type", tradeType);
        //签名
        packageParams.put("sign", createSign(packageParams, AppletConfig.WECHATAPPLET.apiKey));

        return getRequestXml(packageParams);
    }

    /**
     * 获取统一下单请求参数
     *
     * @param orderInfoForPay 订单信息
     * @return 统一下单请求参数
     */
    private static String getWxPayParm(TcOrder orderInfoForPay) {
        SortedMap<String, String> packageParams = new TreeMap<>();
        // 金额转化为分为单位
        int finalmoney = Integer.parseInt(String.format("%.2f", orderInfoForPay.getPayAmount()).replace(".", ""));
        //交易方式
        String tradeType = "JSAPI";
        //用户唯一标识
        packageParams.put("openid", orderInfoForPay.getOpenid());

        //公众账号ID
        packageParams.put("appid", AppletConfig.WECHATAPPLET.appId);
        //商户号
        packageParams.put("mch_id", AppletConfig.WECHATAPPLET.merchantNum);
        //随机字符串
        packageParams.put("nonce_str", getRandomString());
        //商品描述
        packageParams.put("body", "信息发布费-" + orderInfoForPay.getType() + "");
        //附加数据(支付类型) 订单还是充值 店铺编号 支付方式
        // packageParams.put("attach", orderInfoForPay.getType() + "-"+orderInfoForPay.getStoreId()+"-"+wechatSetting.getType());
        packageParams.put("attach", orderInfoForPay.getType() + "");
        //商户订单号
        packageParams.put("out_trade_no", orderInfoForPay.getId() + "-" + getTimeStamp());
        //标价金额
        packageParams.put("total_fee", String.valueOf(finalmoney));
        //终端IP
        packageParams.put("spbill_create_ip", orderInfoForPay.getIp());//本地测试需替换为外网ip
        //通知地址
        packageParams.put("notify_url", AppletConfig.WECHATAPPLET.publishNotice);
        //交易类型
        packageParams.put("trade_type", tradeType);
        //签名
        packageParams.put("sign", createSign(packageParams, AppletConfig.WECHATAPPLET.apiKey));

        return getRequestXml(packageParams);
    }

    /**
     * 获取请求xml
     *
     * @param packageParams 请求参数
     * @return 请求xml
     */
    private static String getRequestXml(SortedMap<String, String> packageParams) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        Set es = packageParams.entrySet();
        for (Object e : es) {
            Map.Entry entry = (Map.Entry) e;
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            if ("body".equalsIgnoreCase(key) || "sign".equalsIgnoreCase(key)) {
                sb.append("<").append(key).append(">").append("<![CDATA[").append(value).append("]]></").append(key).append(">");
            } else {
                sb.append("<").append(key).append(">").append(value).append("</").append(key).append(">");
            }
        }
        sb.append("</xml>");
        log.debug("getRequestXml  and xml:{}", sb.toString());
        return sb.toString();
    }

    /**
     * 签名
     *
     * @param packageParams 签名参数
     * @param apiKey        商户key
     * @return 签名
     */
    private static String createSign(SortedMap<String, String> packageParams, String apiKey) {

        StringBuilder sb = new StringBuilder();
        Set es = packageParams.entrySet();
        for (Object e : es) {
            Map.Entry entry = (Map.Entry) e;
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if ((v != null) && (!"".equals(v)) && (!"sign".equals(k)) &&
                    (!"key".equals(k))) {
                sb.append(k).append("=").append(v).append("&");
            }
        }
        sb.append("key=").append(apiKey);
        log.debug("createSign  and key:{}", apiKey);
        log.debug("createSign  and stringSign:{}", sb.toString());
        String sign = MD5Utils.getInstance().createMd5(sb.toString())
                .toUpperCase();
        log.debug("createSign  and sign:{}", sign);
        return sign;

    }

    /**
     * 获取时间戳
     *
     * @return 时间戳（秒数）
     */
    public static String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000L);
    }

    /**
     * 获取随机字符串
     *
     * @return 随机字符串
     */
    public static String getRandomString() {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 32; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 上传图片
     *
     * @return 返回图片在minio的地址
     * @throws Exception
     */
    @UnAuth
    @PostMapping("tc/uploadToMinio")
    @ApiOperation(value = "上传图片", notes = "上传图片（不需要认证）")
    @Log(title = "tc/uploadToMinio", businessType = BusinessType.SELECT)
    public AjaxResult uploadToMinio(@RequestParam("file") MultipartFile request, String name) throws Exception {
        if (StringUtils.isEmpty(name)) {
            name = "image";
        }
        OssSetting ossSetting = new OssSetting(); //TODO
        ossSetting.setAccessKeyId("");
        ossSetting.setAccessKeySecret("");
        ossSetting.setAddress("");
        ossSetting.setBucketName("");
        ossSetting.setEndPoint("");
       /* OssSetting ossSetting = ossService.queryOssSetting();
        int i = Integer.parseInt(ossSetting.getPrefix()); //1 minio 2 qiniu 3 oss 4 qq云
        if (i == 1) {
            return AjaxResult.success(ossService.uploadToMinio(request, ossSetting));
        } else if (i == 2) {
            return AjaxResult.success(ossService.uploadToQiNiu(request, name, ossSetting));
        } else if (i == 3) {
            return AjaxResult.success(ossService.uploadToOSSYun(request, name, ossSetting));
        } else if (i == 4) {
            return AjaxResult.success(ossService.uploadToQqOSSYun(request, name, ossSetting));
        }*/
        return AjaxResult.success("http://mmbiz.qpic.cn/mmbiz_png/FfMJ58ksTOonicYxTb9dzOn45ricQKzK8YCibk4Htic7RILSZzU3sWLMHJXhciaqb2leOLYD5yoMKmvdeWLjqaKbhng/640?wx_fmt=png");
        //return null;
    }

    /**
     * 新增本地推广
     */
    @Log(title = "本地推广", businessType = BusinessType.INSERT)
    @PostMapping("tc/saveTuiguang")
    public AjaxResult saveTcTuiguang(@RequestBody TcTuiguang tcJob, HttpServletRequest request) {
        Long userId = AppletsLoginUtils.getInstance().getCustomerId(request);
        tcJob.setUserId(userId);
        Long count = tcTuiguangService.countByMonth(userId);
        logger.info("{}发布本地推广{}", userId, count);
        TcMemberLevel level = getTcMemberLevel(userId);
        boolean flag = false;
        TcOrder payRecord = new TcOrder();
        double payAmount = 0;
        if (level != null) {
            tcJob.setStatus("4");
            payAmount = level.getMoreCount();
            if (count >= level.getJobCount()) {
                payRecord.setPublishAmout(payAmount);
                payRecord.setPublishSmsAmout(level.getMoreCount() * level.getTopCount() / 100);
                payAmount = payRecord.getPublishSmsAmout();
                flag = true;
            }
            if (tcJob.getTopId() != null && tcJob.getTopId() > 0) {
                SysDictData dictData = dictDataService.selectDictDataById(tcJob.getTopId());
                tcJob.setIsZhiding("1");
                tcJob.setZhidingTime(DateUtils.addDays(new Date(), Integer.parseInt(dictData.getDictValue())));
                payAmount = level.getMoreCount() * level.getTopCount() / 100 + Long.parseLong(dictData.getDictValue());

                payRecord.setTopDay(Long.parseLong(dictData.getDictValue()));
                payRecord.setTopAmount(BigDecimal.valueOf(Long.parseLong(dictData.getDictValue())));
                flag = true;
            }
        }
        if (flag) {
            tcTuiguangService.insertTcTuiguang(tcJob);
            payRecord.setTitle(tcJob.getName());

            saveTcPreOrder(userId, level, payRecord, payAmount);
            return AjaxResult.success(payRecord);
        } else {
            tcJob.setStatus("1");
            return toAjax(tcTuiguangService.insertTcTuiguang(tcJob));
        }
    }

    /**
     * 新增招聘信息
     */
    @Log(title = "招聘信息", businessType = BusinessType.INSERT)
    @PostMapping("tc/saveJob")
    public AjaxResult saveJob(@RequestBody TcJob tcJob, HttpServletRequest request) {
        Long userId = AppletsLoginUtils.getInstance().getCustomerId(request);
        tcJob.setUserId(userId);
        Long count = tcJobService.countByMonth(userId);
        logger.info("{}发布招聘信息{}", userId, count);
        TcMemberLevel level = getTcMemberLevel(userId);
        boolean flag = false;
        TcOrder payRecord = new TcOrder();
        double payAmount = 0;
        if (level != null) {
            tcJob.setStatus("4");
            payAmount = level.getMoreCount();
            if (count >= level.getJobCount()) {
                payRecord.setPublishAmout(payAmount);
                payRecord.setPublishSmsAmout(level.getMoreCount() * level.getTopCount() / 100);
                payAmount = payRecord.getPublishSmsAmout();
                flag = true;
            }
            if (tcJob.getTopId() != null && tcJob.getTopId() > 0) {
                SysDictData dictData = dictDataService.selectDictDataById(tcJob.getTopId());
                tcJob.setIsZhiding("1");
                tcJob.setZhidingTime(DateUtils.addDays(new Date(), Integer.parseInt(dictData.getDictValue())));
                payAmount = level.getMoreCount() * level.getTopCount() / 100 + Long.parseLong(dictData.getDictValue());

                payRecord.setTopDay(Long.parseLong(dictData.getDictValue()));
                payRecord.setTopAmount(BigDecimal.valueOf(Long.parseLong(dictData.getDictValue())));
                flag = true;
            }
        }
        if (flag) {
            tcJobService.insertTcJob(tcJob);
            payRecord.setTitle(tcJob.getName());

            saveTcPreOrder(userId, level, payRecord, payAmount);
            return AjaxResult.success(payRecord);
        } else {
            tcJob.setStatus("1");
            return toAjax(tcJobService.insertTcJob(tcJob));
        }
    }

    /**
     * 新增生意转让
     */
    @Log(title = "生意转让", businessType = BusinessType.INSERT)
    @PostMapping("tc/saveZhuanlang")
    public AjaxResult saveTcZhuanlang(@RequestBody TcZhuanlang tcJob, HttpServletRequest request) {
        return AjaxResult.success();
    }

    /**
     * 新增物品信息
     */
    @Log(title = "物品信息", businessType = BusinessType.INSERT)
    @PostMapping("tc/saveGoods")
    public AjaxResult saveGoods(@RequestBody TcGoods tcJob, HttpServletRequest request) {
        Long userId = AppletsLoginUtils.getInstance().getCustomerId(request);
        tcJob.setUserId(userId);
        Long count = tcGoodsService.countByMonth(userId);
        logger.info("{}发布物品信息{}", userId, count);
        TcMemberLevel level = getTcMemberLevel(userId);
        boolean flag = false;
        double payAmount = 0;
        TcOrder payRecord = new TcOrder();
        if (level != null) {
            tcJob.setStatus("4");

            payAmount = level.getMoreCount();
            if (count >= level.getJobCount()) {
                payRecord.setPublishAmout(payAmount);
                payRecord.setPublishSmsAmout(level.getMoreCount() * level.getTopCount() / 100);
                payAmount = payRecord.getPublishSmsAmout();
                flag = true;
            }
            if (tcJob.getTopId() != null && tcJob.getTopId() > 0) {
                SysDictData dictData = dictDataService.selectDictDataById(tcJob.getTopId());
                tcJob.setIsZhiding("1");
                tcJob.setZhidingTime(DateUtils.addDays(new Date(), Integer.parseInt(dictData.getDictValue())));
                payAmount = level.getMoreCount() * level.getTopCount() / 100 + Long.parseLong(dictData.getDictValue());

                payRecord.setTopDay(Long.parseLong(dictData.getDictValue()));
                payRecord.setTopAmount(BigDecimal.valueOf(Long.parseLong(dictData.getDictValue())));
                flag = true;
            }
        }
        if (flag) {
            tcGoodsService.insertTcGoods(tcJob);
            payRecord.setTitle(tcJob.getName());

            saveTcPreOrder(userId, level, payRecord, payAmount);
            return AjaxResult.success(payRecord);
        } else {
            tcJob.setStatus("1");
            return toAjax(tcGoodsService.insertTcGoods(tcJob));
        }
    }

    /**
     * 新增农林牧渔对象
     */
    @Log(title = "农林牧渔对象", businessType = BusinessType.INSERT)
    @PostMapping("tc/saveNonglin")
    public AjaxResult saveTcNonglin(@RequestBody TcNonglin tcJob, HttpServletRequest request) {
        Long userId = AppletsLoginUtils.getInstance().getCustomerId(request);
        tcJob.setUserId(userId);
        Long count = tcNonglinService.countByMonth(userId);
        logger.info("{}发布农林牧渔对象{}", userId, count);
        TcMemberLevel level = getTcMemberLevel(userId);
        boolean flag = false;
        TcOrder payRecord = new TcOrder();
        double payAmount = 0;
        if (level != null) {
            tcJob.setStatus("4");

            payAmount = level.getMoreCount();
            if (count >= level.getNongCount()) {
                payRecord.setPublishAmout(payAmount);
                payRecord.setPublishSmsAmout(level.getMoreCount() * level.getTopCount() / 100);
                payAmount = payRecord.getPublishSmsAmout();
                flag = true;
            }
            if (tcJob.getTopId() != null && tcJob.getTopId() > 0) {
                SysDictData dictData = dictDataService.selectDictDataById(tcJob.getTopId());
                tcJob.setIsZhiding("1");
                tcJob.setZhidingTime(DateUtils.addDays(new Date(), Integer.parseInt(dictData.getDictValue())));
                payAmount = level.getMoreCount() * level.getTopCount() / 100 + Long.parseLong(dictData.getDictValue());

                payRecord.setTopDay(Long.parseLong(dictData.getDictValue()));
                payRecord.setTopAmount(BigDecimal.valueOf(Long.parseLong(dictData.getDictValue())));
                flag = true;
            }

        }
        if (flag) {
            tcNonglinService.insertTcNonglin(tcJob);
            payRecord.setTitle(tcJob.getName());

            saveTcPreOrder(userId, level, payRecord, payAmount);
            return AjaxResult.success(payRecord);
        } else {
            tcJob.setStatus("1");
            return toAjax(tcNonglinService.insertTcNonglin(tcJob));
        }
    }

    /**
     * 新增求购对象
     */
    @Log(title = "求购对象", businessType = BusinessType.INSERT)
    @PostMapping("tc/saveQiugou")
    public AjaxResult saveTcQiugou(@RequestBody TcQiugou tcJob, HttpServletRequest request) {
        Long userId = AppletsLoginUtils.getInstance().getCustomerId(request);
        tcJob.setUserId(userId);
        Long count = tcQiugouService.countByMonth(userId);
        logger.info("{}发布求购信息{}", userId, count);
        TcMemberLevel level = getTcMemberLevel(userId);
        boolean flag = false;
        TcOrder payRecord = new TcOrder();
        double payAmount = 0;
        if (level != null) {
            tcJob.setStatus("4");

            payAmount = level.getMoreCount();
            if (count >= level.getSpeakCount()) {
                payRecord.setPublishAmout(payAmount);
                payRecord.setPublishSmsAmout(level.getMoreCount() * level.getTopCount() / 100);
                payAmount = payRecord.getPublishSmsAmout();
                flag = true;
            }
            if (tcJob.getTopId() != null && tcJob.getTopId() > 0) {
                SysDictData dictData = dictDataService.selectDictDataById(tcJob.getTopId());
                tcJob.setIsZhiding("1");
                tcJob.setZhidingTime(DateUtils.addDays(new Date(), Integer.parseInt(dictData.getDictValue())));
                payAmount = level.getMoreCount() * level.getTopCount() / 100 + Long.parseLong(dictData.getDictValue());

                payRecord.setTopDay(Long.parseLong(dictData.getDictValue()));
                payRecord.setTopAmount(BigDecimal.valueOf(Long.parseLong(dictData.getDictValue())));
                flag = true;
            }
        }
        if (flag) {
            tcQiugouService.insertTcQiugou(tcJob);
            payRecord.setTitle(tcJob.getName());

            saveTcPreOrder(userId, level, payRecord, payAmount);
            return AjaxResult.success(payRecord);
        } else {
            tcJob.setStatus("1");
            return toAjax(tcQiugouService.insertTcQiugou(tcJob));
        }
    }

    /**
     * 新增房屋信息
     */
    @Log(title = "房屋信息", businessType = BusinessType.INSERT)
    @PostMapping("tc/saveRoom")
    public AjaxResult saveTcRoom(@RequestBody TcRoom tcJob, HttpServletRequest request) {
        Long userId = AppletsLoginUtils.getInstance().getCustomerId(request);
        tcJob.setUserId(userId);
        Long count = tcRoomService.countByMonth(userId);
        logger.info("{}发布房屋信息{}", userId, count);
        TcMemberLevel level = getTcMemberLevel(userId);
        boolean flag = false;
        TcOrder payRecord = new TcOrder();
        double payAmount = 0;
        if (level != null) {
            tcJob.setStatus("4");

            payAmount = level.getMoreCount();
            if (count >= level.getRoomCount()) {
                payRecord.setPublishAmout(payAmount);
                payRecord.setPublishSmsAmout(level.getMoreCount() * level.getTopCount() / 100);
                payAmount = payRecord.getPublishSmsAmout();
                flag = true;
            }
            if (tcJob.getTopId() != null && tcJob.getTopId() > 0) {
                SysDictData dictData = dictDataService.selectDictDataById(tcJob.getTopId());
                tcJob.setIsZhiding("1");
                tcJob.setZhidingTime(DateUtils.addDays(new Date(), Integer.parseInt(dictData.getDictValue())));
                payAmount = level.getMoreCount() * level.getTopCount() / 100 + Long.parseLong(dictData.getDictValue());

                payRecord.setTopDay(Long.parseLong(dictData.getDictValue()));
                payRecord.setTopAmount(BigDecimal.valueOf(Long.parseLong(dictData.getDictValue())));
                flag = true;
            }

        }
        if (flag) {
            tcRoomService.insertTcRoom(tcJob);
            payRecord.setTitle(tcJob.getName());

            saveTcPreOrder(userId, level, payRecord, payAmount);
            return AjaxResult.success(payRecord);
        } else {
            tcJob.setStatus("1");
            return toAjax(tcRoomService.insertTcRoom(tcJob));
        }
    }

    /**
     * 新增车况信息
     */
    @Log(title = "新增车况信息", businessType = BusinessType.INSERT)
    @PostMapping("tc/saveCar")
    public AjaxResult saveTcCar(@RequestBody TcCar tcJob, HttpServletRequest request) {
        Long userId = AppletsLoginUtils.getInstance().getCustomerId(request);
        tcJob.setUserId(userId);
        if (tcJob.getShangpaiTimes() != null) {
            tcJob.setShangpaiTime(new Date(tcJob.getShangpaiTimes() * 1000));
        }
        Long count = tcCarService.countByMonth(userId);
        logger.info("{}发布车况信息{}", userId, count);
        TcMemberLevel level = getTcMemberLevel(userId);
        boolean flag = false;
        double payAmount = 0;
        TcOrder payRecord = new TcOrder();
        if (level != null) {
            tcJob.setStatus("4");

            payAmount = level.getMoreCount();
            if (count >= level.getCarCount()) {
                payRecord.setPublishAmout(payAmount);
                payRecord.setPublishSmsAmout(level.getMoreCount() * level.getTopCount() / 100);
                payAmount = payRecord.getPublishSmsAmout();
                flag = true;
            }
            if (tcJob.getTopId() != null && tcJob.getTopId() > 0) {
                SysDictData dictData = dictDataService.selectDictDataById(tcJob.getTopId());
                tcJob.setIsZhiding("1");
                tcJob.setZhidingTime(DateUtils.addDays(new Date(), Integer.parseInt(dictData.getDictValue())));
                payAmount = level.getMoreCount() * level.getTopCount() / 100 + Long.parseLong(dictData.getDictValue());

                payRecord.setTopDay(Long.parseLong(dictData.getDictValue()));
                payRecord.setTopAmount(BigDecimal.valueOf(Long.parseLong(dictData.getDictValue())));
                flag = true;
            }
        }
        if (flag) {
            tcCarService.insertTcCar(tcJob);
            payRecord.setTitle(tcJob.getName());

            saveTcPreOrder(userId, level, payRecord, payAmount);
            return AjaxResult.success(payRecord);
        } else {
            tcJob.setStatus("1");
            return toAjax(tcCarService.insertTcCar(tcJob));
        }
    }

    /**
     * 新增个人简历和修改
     */
    @Log(title = "个人简历", businessType = BusinessType.INSERT)
    @PostMapping("tc/saveUserCard")
    public AjaxResult saveTcUserCard(@RequestBody TcUserCard tcJob, HttpServletRequest request) {
        if (tcJob.getId() != null) {
            return toAjax(userCardService.updateTcUserCard(tcJob));
        }
        Long userId = AppletsLoginUtils.getInstance().getCustomerId(request);
        tcJob.setUserId(userId);
        tcJob.setStatus("1");
        return toAjax(userCardService.insertTcUserCard(tcJob));
    }

    /**
     * 商户入驻和修改
     */
    @Log(title = "商户入驻和修改", businessType = BusinessType.INSERT)
    @PostMapping("tc/saveStore")
    public AjaxResult saveStore(@RequestBody TcStoreInfo tcJob, HttpServletRequest request) {
        if (tcJob.getId() != null) {
            return toAjax(tcStoreInfoService.updateTcStoreInfo(tcJob));
        }
        Long userId = AppletsLoginUtils.getInstance().getCustomerId(request);
        tcJob.setUserId(userId);
        tcJob.setStatus("4");
        tcStoreInfoService.insertTcStoreInfo(tcJob);
        return AjaxResult.success(tcJob.getId());
    }

    /**
     * 商户点评
     */
    @Log(title = "商户点评", businessType = BusinessType.INSERT)
    @PostMapping("tc/saveStoreComment")
    public AjaxResult saveStoreComment(@RequestBody TcStroeComment tcJob, HttpServletRequest request) {

        Long userId = AppletsLoginUtils.getInstance().getCustomerId(request);
        TcMember member = tcMemberService.selectTcMemberById(userId);
        if (member!=null){
            tcJob.setUserId(userId);
            tcJob.setUserName(member.getUsername());
            tcJob.setUserPic(member.getImage());
        }else {
            tcJob.setUserName("匿名");
            tcJob.setUserPic("https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLTPNEcNnBGthW5lg6gbaMuj0tgddVqePyQiaEY7V9EvGVQLfPg6Gic8M4byTx0icKd0MHzVSKBAwpzQ/132");
        }
        stroeCommentService.insertTcStroeComment(tcJob);
        TcStoreInfo storeInfo = tcStoreInfoService.selectTcStoreInfoById(tcJob.getStoreId());
        storeInfo.setScope(storeInfo.getScope() + Long.parseLong(tcJob.getScope()));
        tcStoreInfoService.updateTcStoreInfo(storeInfo);
        return AjaxResult.success(tcJob.getId());
    }

    /**
     * 开通会员
     */
    @Log(title = "开通会员", businessType = BusinessType.INSERT)
    @PostMapping("tc/openVip")
    public AjaxResult openVip(@RequestBody TcMemberLevelVo tcJob, HttpServletRequest request) {
        if (StringUtils.isEmpty(tcJob.getMonth()) || StringUtils.isEmpty(tcJob.getPrice())
                || tcJob.getId() < 1) {
            return AjaxResult.error();
        }
        Long userId = AppletsLoginUtils.getInstance().getCustomerId(request);
        TcDepositRecord record = new TcDepositRecord();
        record.setCustomerId(userId);
        record.setMonthCount(Long.parseLong(tcJob.getMonth()));
        List<TcDepositRecord> list = depositRecordService.selectTcDepositRecordList(record);
        if (list != null && list.size() > 0) {
            TcDepositRecord depositRecord = list.stream().filter(ruleInfo -> ruleInfo.getCloseTime().after(new Date())).findFirst().orElse(null);
            if (depositRecord != null) {
                return AjaxResult.success(-1);
            }
            return AjaxResult.success(list.get(0).getId());
        }
        record.setMemberLevelId(tcJob.getId());
        record.setStatus("1");
        record.setPayAmount(BigDecimal.valueOf(tcJob.getPrice()));
        depositRecordService.insertTcDepositRecord(record);
        return AjaxResult.success(tcJob.getId());
    }

    /**
     * 开通会员
     */
    @Log(title = "开通会员", businessType = BusinessType.INSERT)
    @PostMapping("tc/payOpenVip")
    public AjaxResult payOpenVip(@RequestBody TcPayVo tcJob, HttpServletRequest request) {
        log.debug("payOpenVip and TcPayVo:{}", tcJob);
        Long userId = AppletsLoginUtils.getInstance().getCustomerId(request);
        TcMember baseUser = memberService.selectTcMemberById(userId);
        if (baseUser == null) {
            throw new ServiceException("用户不存在");
        }
        TcDepositRecord orderBase = depositRecordService.selectTcDepositRecordById(tcJob.getId());
        if (orderBase == null) {
            throw new ServiceException("充值记录不存在");
        }

        orderBase.setOpenid(baseUser.getAppletOpenId());
        orderBase.setIp(getIpAddr(request));
        // 小程序统一下单，tradeType也是"JSAPI"
        PrepayResult prepayResult = this.getPrepay(orderBase);
        if (prepayResult == null) {
            log.error(" ~~ 调起微信支付面板失败 ！！ 请求参数：" + JSONUtils.toJson(prepayResult));
            throw new ServiceException("微信支付系统繁忙，请稍后再试");
        }
        return AjaxResult.success(prepayResult);
    }

    /**
     * 超过免费发布数量后 支付
     */
    @Log(title = "超过免费发布数量后 支付", businessType = BusinessType.INSERT)
    @PostMapping("tc/payPublishVip")
    public AjaxResult payPublishVip(@RequestBody TcOrder tcJob, HttpServletRequest request) {
        log.debug("payPublishVip and TcPayVo:{}", tcJob);
        Long userId = AppletsLoginUtils.getInstance().getCustomerId(request);
        TcMember baseUser = memberService.selectTcMemberById(userId);
        if (baseUser == null) {
            throw new ServiceException("用户不存在");
        }
        tcJob = orderService.selectTcOrderById(tcJob.getId());
        if (tcJob == null) {
            throw new ServiceException("充值记录不存在");
        }

        tcJob.setOpenid(baseUser.getAppletOpenId());
        tcJob.setIp(getIpAddr(request));
        // 小程序统一下单，tradeType也是"JSAPI"
        PrepayResult prepayResult = this.getPrepay(tcJob);
        if (prepayResult == null) {
            log.error(" ~~ 调起微信支付面板失败 ！！ 请求参数：" + JSONUtils.toJson(prepayResult));
            throw new ServiceException("微信支付系统繁忙，请稍后再试");
        }
        return AjaxResult.success(prepayResult);
    }

    /**
     * 微信支付回调
     */
    @RequestMapping("/tc/openvipNotice")
    @UnAuth
    @ApiIgnore
    @Log(title = "微信支付回调", businessType = BusinessType.SELECT)
    public void openvipNotice(HttpServletRequest request, HttpServletResponse response) throws IOException {
        TcDepositRecord orderInfoAfterPay = this.afterPayInfo(request.getInputStream());
        TcDepositRecord record = depositRecordService.selectTcDepositRecordById(orderInfoAfterPay.getId());
        orderInfoAfterPay.setCloseTime(DateUtils.addDays(new Date(), record.getMonthCount().intValue() * 30));
        if (depositRecordService.updateTcDepositRecord(orderInfoAfterPay) > 0) {
            sendMessage(response, WechatUtils.SUCCESS_RETURN);
        }
    }

    /**
     * 微信支付回调
     */
    @RequestMapping("/tc/publishNotice")
    @UnAuth
    @ApiIgnore
    @Log(title = "微信支付回调", businessType = BusinessType.SELECT)
    public void publishNotice(HttpServletRequest request, HttpServletResponse response) throws IOException {
        InputStream inputStream = request.getInputStream();
        TcOrder orderInfoAfterPay = new TcOrder();
        BufferedReader br;
        br = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuilder sb = new StringBuilder();
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                br.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //将xml字符串转换为java对象
        JaxbUtil resultBinder = new JaxbUtil(WechatNotifyResult.class);
        WechatNotifyResult wechatNotifyResult = resultBinder.fromXml(sb.toString());
        //将xml字符串转换为map
        SortedMap<String, String> resultMap = new TreeMap<>(parseMapFromXmlStr(sb.toString()));
        //签名
        String sign = createSign(resultMap, AppletConfig.WECHATAPPLET.apiKey);

        log.info("wechat notify and wechatNotifyResult :{}", wechatNotifyResult);

        //验证是否失败，并验证签名
        if (!wechatNotifyResult.isError() && sign.equals(wechatNotifyResult.getSign())) {
            //验证其他信息
            if (SUCCESS.equals(wechatNotifyResult.getResult_code())
                    && SUCCESS.equals(wechatNotifyResult.getReturn_code())
                    && AppletConfig.WECHATAPPLET.appId.equals(wechatNotifyResult.getAppid())
                    && AppletConfig.WECHATAPPLET.merchantNum.equals(wechatNotifyResult.getMch_id())) {
                orderInfoAfterPay.setId(Long.parseLong(wechatNotifyResult.getOut_trade_no().split("-")[0]));
                orderInfoAfterPay.setStatus("2");
                orderInfoAfterPay.setOutTradeNo(wechatNotifyResult.getTransaction_id());
                // orderInfoAfterPay.setType(wechatNotifyResult.getAttach());
                int type = Integer.parseInt(wechatNotifyResult.getAttach().split(",")[1]);
                if (type == 1) {
                    TcRoom room = new TcRoom();
                    room.setStatus("1");
                    room.setId(Long.parseLong(wechatNotifyResult.getAttach().split(",")[2]));
                    tcRoomService.updateTcRoom(room);
                } else if (type == 2) {
                    TcNonglin room = new TcNonglin();
                    room.setStatus("1");
                    room.setId(Long.parseLong(wechatNotifyResult.getAttach().split(",")[2]));
                    tcNonglinService.updateTcNonglin(room);
                } else if (type == 3) {
                    TcGoods room = new TcGoods();
                    room.setStatus("1");
                    room.setId(Long.parseLong(wechatNotifyResult.getAttach().split(",")[2]));
                    tcGoodsService.updateTcGoods(room);
                } else if (type == 4) {
                    TcTuiguang room = new TcTuiguang();
                    room.setStatus("1");
                    room.setId(Long.parseLong(wechatNotifyResult.getAttach().split(",")[2]));
                    tcTuiguangService.updateTcTuiguang(room);
                } else if (type == 5) {
                    TcQiugou room = new TcQiugou();
                    room.setStatus("1");
                    room.setId(Long.parseLong(wechatNotifyResult.getAttach().split(",")[2]));
                    tcQiugouService.updateTcQiugou(room);
                } else if (type == 6) {
                    TcJob room = new TcJob();
                    room.setStatus("1");
                    room.setId(Long.parseLong(wechatNotifyResult.getAttach().split(",")[2]));
                    tcJobService.updateTcJob(room);
                } else if (type == 8) {
                    TcZhuanlang room = new TcZhuanlang();
                    room.setStatus("1");
                    room.setId(Long.parseLong(wechatNotifyResult.getAttach().split(",")[2]));
                    tcZhuanlangService.updateTcZhuanlang(room);
                } else if (type == 10) {
                    TcCar room = new TcCar();
                    room.setStatus("1");
                    room.setId(Long.parseLong(wechatNotifyResult.getAttach().split(",")[2]));
                    tcCarService.updateTcCar(room);
                }
            }

        } else {
            log.error("wechat afterPayInfo fail: returnmsg:{}\r\n errormsg:{}", wechatNotifyResult.getReturn_msg(), wechatNotifyResult.getErr_code_des());
        }
        if (orderService.updateTcOrder(orderInfoAfterPay) > 0) {
            sendMessage(response, WechatUtils.SUCCESS_RETURN);
        }
    }

    /**
     * 回传信息
     *
     * @param message 信息
     */
    private void sendMessage(HttpServletResponse response, String message) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.println(message);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }

    }

    private void saveTcPreOrder(Long userId, TcMemberLevel level, TcOrder payRecord, double payAmount) {
        payRecord.setStatus("1");
        payRecord.setCustomerId(userId);
        payRecord.setPayAmount(BigDecimal.valueOf(payAmount));
        payRecord.setCreateTime(new Date());
        payRecord.setMemberLevel(level.getId());
        payRecord.setOrderNo(String.valueOf(snowflakeIdWorker.nextId()));
        orderService.insertTcOrder(payRecord);
    }

    private TcMemberLevel getTcMemberLevel(Long userId) {
        TcDepositRecord record = new TcDepositRecord();
        record.setCustomerId(userId);
        record.setStatus("2");
        List<TcDepositRecord> list = depositRecordService.selectTcDepositRecordList(record);
        TcDepositRecord depositRecord = list.stream().filter(ruleInfo -> ruleInfo.getCloseTime().after(new Date())).findFirst().orElse(null);
        TcMemberLevel level = new TcMemberLevel();
        if (depositRecord != null) {
            level = memberLevelService.selectTcMemberLevelById(depositRecord.getMemberLevelId());
        } else {
            level = memberLevelService.selectTcMemberLevelById(AppletConfig.defaultMemberLevel);
        }
        return level;
    }

    /**
     * 获取ip地址
     */
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip != null && ip.indexOf(",") > -1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
}
